import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:family_app/src/features/secure_vault/models/vault_item_model.dart';
import 'package:family_app/src/features/secure_vault/providers/secure_vault_provider.dart';
import 'package:family_app/src/features/secure_vault/widgets/add_vault_item_dialog.dart';
import 'package:family_app/src/features/secure_vault/widgets/vault_item_detail.dart';
import 'package:family_app/src/features/secure_vault/widgets/vault_item_list_tile.dart';
import 'package:family_app/src/theme/app_theme.dart';
import 'package:family_app/src/common/widgets/app_header.dart';

/// 私密信息管理主界面
class SecureVaultScreen extends ConsumerStatefulWidget {
  const SecureVaultScreen({Key? key}) : super(key: key);

  @override
  ConsumerState<SecureVaultScreen> createState() => _SecureVaultScreenState();
}

class _SecureVaultScreenState extends ConsumerState<SecureVaultScreen>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  final TextEditingController _searchController = TextEditingController();
  bool _isSearching = false;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 6, vsync: this);
    _tabController.addListener(_handleTabChange);
  }

  @override
  void dispose() {
    _tabController.removeListener(_handleTabChange);
    _tabController.dispose();
    _searchController.dispose();
    super.dispose();
  }

  /// 处理标签页变化
  void _handleTabChange() {
    if (_tabController.indexIsChanging) {
      // 清空搜索
      if (_isSearching) {
        setState(() {
          _isSearching = false;
          _searchController.clear();
        });
        ref.read(searchQueryProvider.notifier).state = '';
      }

      // 更新选中的类型
      if (_tabController.index == 0) {
        // 全部
        ref.read(selectedVaultTypeProvider.notifier).state = null;
      } else if (_tabController.index == 5) {
        // 收藏
        ref.read(selectedVaultTypeProvider.notifier).state = null;
      } else {
        // 特定类型
        final type = VaultItemType.values[_tabController.index - 1];
        ref.read(selectedVaultTypeProvider.notifier).state = type;
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final operationState = ref.watch(vaultOperationProvider);

    // 显示操作状态提示
    _showOperationMessage(context, operationState);

    return Scaffold(
      appBar: AppHeader(
        title: _isSearching ? '' : '密码库',
        showBackButton: true,
        actions: [
          IconButton(
            icon: Icon(_isSearching ? Icons.close : Icons.search),
            onPressed: () {
              setState(() {
                _isSearching = !_isSearching;
                if (!_isSearching) {
                  _searchController.clear();
                  ref.read(searchQueryProvider.notifier).state = '';
                }
              });
            },
          ),
          IconButton(
            icon: const Icon(Icons.add),
            onPressed: () => _showAddVaultItemDialog(context),
          ),
        ],
      ),
      body: Column(
        children: [
          if (_isSearching)
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
              child: TextField(
                controller: _searchController,
                autofocus: true,
                decoration: InputDecoration(
                  hintText: '搜索密码...',
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(8.r),
                  ),
                  prefixIcon: const Icon(Icons.search),
                  hintStyle: TextStyle(color: Colors.grey[400]),
                ),
                onChanged: (value) {
                  ref.read(searchQueryProvider.notifier).state = value;
                },
              ),
            ),
          // 在这里添加 TabBar
          TabBar(
            controller: _tabController,
            isScrollable: true,
            labelColor: AppTheme.primaryColor,
            unselectedLabelColor: Colors.grey,
            indicatorColor: AppTheme.primaryColor,
            tabs: const [
              Tab(text: '全部'),
              Tab(text: '网站'),
              Tab(text: '应用'),
              Tab(text: '银行卡'),
              Tab(text: '证件'),
              Tab(text: '收藏'),
            ],
          ),
          // 使用 Expanded 包裹 TabBarView
          Expanded(
            child: TabBarView(
              controller: _tabController,
              children: [
                // 全部
                _buildVaultItemsList(ref.watch(vaultItemsProvider)),
                // 网站
                _buildVaultItemsList(ref.watch(vaultItemsProvider)),
                // 应用
                _buildVaultItemsList(ref.watch(vaultItemsProvider)),
                // 银行卡
                _buildVaultItemsList(ref.watch(vaultItemsProvider)),
                // 证件
                _buildVaultItemsList(ref.watch(vaultItemsProvider)),
                // 收藏
                _buildVaultItemsList(ref.watch(favoriteVaultItemsProvider)),
              ],
            ),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => _showAddVaultItemDialog(context),
        backgroundColor: AppTheme.primaryColor,
        child: const Icon(Icons.add),
      ),
    );
  }

  /// 构建私密信息项列表
  Widget _buildVaultItemsList(AsyncValue<List<VaultItemModel>> itemsAsync) {
    return itemsAsync.when(
      data: (items) {
        if (items.isEmpty) {
          return _buildEmptyState();
        }

        return ListView.builder(
          padding: EdgeInsets.symmetric(vertical: 8.h),
          itemCount: items.length,
          itemBuilder: (context, index) {
            final item = items[index];
            return VaultItemListTile(
              item: item,
              onTap: () => _showVaultItemDetail(context, item),
              onFavoriteToggle: () {
                ref
                    .read(vaultOperationProvider.notifier)
                    .toggleFavorite(item.id);
              },
              onDelete: () => _showDeleteVaultItemDialog(context, item),
            );
          },
        );
      },
      loading: () => const Center(child: CircularProgressIndicator()),
      error: (error, stack) => Center(
        child: Text('加载失败: $error', style: TextStyle(color: Colors.red)),
      ),
    );
  }

  /// 构建空状态
  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.lock_outline, size: 64.r, color: Colors.grey),
          SizedBox(height: 16.h),
          Text(
            '暂无私密信息',
            style: TextStyle(fontSize: 16.sp, color: Colors.grey),
          ),
          SizedBox(height: 16.h),
          ElevatedButton.icon(
            onPressed: () => _showAddVaultItemDialog(context),
            icon: const Icon(Icons.add),
            label: const Text('添加信息'),
            style: ElevatedButton.styleFrom(
              backgroundColor: AppTheme.primaryColor,
              foregroundColor: Colors.white,
            ),
          ),
        ],
      ),
    );
  }

  /// 显示添加私密信息对话框
  void _showAddVaultItemDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AddVaultItemDialog(
        onSubmit: (title, type, username, password, url, notes) async {
          Navigator.of(context).pop();
          await ref.read(vaultOperationProvider.notifier).addVaultItem(
                title: title,
                type: type,
                username: username,
                password: password,
                url: url,
                notes: notes,
              );
        },
      ),
    );
  }

  /// 显示私密信息详情
  void _showVaultItemDetail(BuildContext context, VaultItemModel item) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.vertical(top: Radius.circular(16.r))),
      builder: (context) => VaultItemDetail(
        item: item,
        onEdit: () {
          Navigator.of(context).pop();
          _showEditVaultItemDialog(context, item);
        },
        onDelete: () {
          Navigator.of(context).pop();
          _showDeleteVaultItemDialog(context, item);
        },
      ),
    );
  }

  /// 显示编辑私密信息对话框
  void _showEditVaultItemDialog(BuildContext context, VaultItemModel item) {
    showDialog(
      context: context,
      builder: (context) => AddVaultItemDialog(
        title: '编辑信息',
        submitButtonText: '保存',
        initialTitle: item.title,
        initialType: item.type,
        initialUsername: item.username,
        initialPassword: item.password,
        initialUrl: item.url,
        initialNotes: item.notes,
        onSubmit: (title, type, username, password, url, notes) async {
          Navigator.of(context).pop();
          await ref.read(vaultOperationProvider.notifier).updateVaultItem(
                id: item.id,
                title: title,
                type: type,
                username: username,
                password: password,
                url: url,
                notes: notes,
              );
        },
      ),
    );
  }

  /// 显示删除私密信息确认对话框
  void _showDeleteVaultItemDialog(BuildContext context, VaultItemModel item) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('删除信息'),
        content: Text('确定要删除「${item.title}」吗？此操作不可恢复。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () async {
              Navigator.of(context).pop();
              await ref
                  .read(vaultOperationProvider.notifier)
                  .deleteVaultItem(item.id);
            },
            style: TextButton.styleFrom(foregroundColor: Colors.red),
            child: const Text('删除'),
          ),
        ],
      ),
    );
  }

  /// 显示操作状态提示
  void _showOperationMessage(BuildContext context, VaultOperationState state) {
    if (state.isSuccess && state.message != null) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(state.message!)),
        );
      });
    } else if (!state.isSuccess && state.error != null) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(state.error!),
            backgroundColor: Colors.red,
          ),
        );
      });
    }
  }
}
